import Taro from "@tarojs/taro"
import {getStorage} from "../../utils"
import {getGlobalData,setGlobalData} from "./global/global"
const storage = getStorage()
var MyUtils = {
  getQueryVariable(variable) {//路由中获取参数
    if(process.env.TARO_ENV === "h5"){
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return undefined;
    }else if(process.env.TARO_ENV === "weapp"){
      let RouterParmas = Taro.getCurrentInstance().router?.params
      if(!RouterParmas)return undefined
      return RouterParmas[variable] || undefined
    }
  },
  //选择文件
  chooseFile:function(option){
    const {count=1, success, fail, complete} = option
    const res:any = {
      errMsg:'chooseFile:ok',
      tempFilePaths: [],
      tempFiles: []
    }
    if(count && typeof count !== 'number'){
      res.errMsg = 'error,typeof count is error',
      console.error(res.errMsg)
      typeof fail === 'function' && fail(res)
      typeof complete === 'function' && complete(res)
      return Promise.reject(res)
    }

    if(Taro.getEnv() === Taro.ENV_TYPE.WEB){
      const fileId = "MyUtilsChooseFile"
      let taroChooseImageId:any = document.getElementById(fileId)
      if(!taroChooseImageId){
        let htmlInputElement: any = document.createElement("input");
        htmlInputElement.type = "file"
        htmlInputElement.setAttribute('id',fileId)
        htmlInputElement.setAttribute('style', 'position: fixed; top: -4000px; left: -3000px; z-index: -300;')
        if(count>1){
          htmlInputElement.setAttribute('multiple', 'multiple')
        }
        document.body.appendChild(htmlInputElement)
        taroChooseImageId = document.getElementById(fileId)
      }else{
        if(count>1){
          taroChooseImageId.setAttribute('multiple', 'multiple')
        }else{
          taroChooseImageId.removeAttribute("multiple")
        }
      }
      
      // htmlInputElement.accept = "application/*"
      // htmlInputElement.accept = "application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      // htmlInputElement.accept = "image/jpeg,image/gif,image/png"

      taroChooseImageId.onchange = (e) => {
        // console.log("onchange",e)
        let arr = [...e.target.files]
        arr = arr.splice(0, count)
        arr && arr.forEach(item=>{
          let blob = new Blob([item], {
            type: e.target.files[0].type
          });
          let url = URL.createObjectURL(blob);
          res.tempFilePaths.push(url)
          // res.tempFiles.push({path: url, size: item.size, type: item.type, originalFileObj: item})
          console.log("选择item",item)
          res.tempFiles.push({
            path:url,
            size:item.size,
            type: item.type,
            name:item.name,
            lastModified:item.lastModified,
            lastModifiedDate:item.lastModifiedDate,
            webkitRelativePath:item.webkitRelativePath
          })
        })
        typeof success === "function" && success(res)
        typeof complete === "function" && complete(res)

        e.target.value = ''
        // document.body.removeChild(taroChooseImageId)
      }
      //触发选择
      taroChooseImageId.click()
      
    }else{
      Taro.chooseMessageFile({
        count: count,
        type: 'file',
        success: function (res) {
          // console.log("选择文件",res)
          success?success(res):""
        }
      })
    }
  },
  //选择图片
  choosePic:function(count=8){
    return new Promise((resolve,reject)=>{
      Taro.chooseImage({
        count: count, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          console.log("选择图片信息",res)
          if(process.env.TARO_ENV === 'h5'){
            resolve(res)
          }else{
            let tempFiles:any = res.tempFiles
            tempFiles = tempFiles.map(item=>{
              return {
                path:item.path,
                size:item.size,
                originalFileObj:{
                  name: MyUtils.getFileName(item.path)
                }
              }
            })
            resolve({
              errMsg:res.errMsg,
              tempFilePaths:res.tempFilePaths,
              tempFiles:tempFiles
            })
          }
          // var tempFilePaths = res.tempFilePaths
          // resolve(tempFilePaths)
        },
        fail:function(res){
          reject(res)
        }
      })
    }) 
  },
  //预览图片
  previewPic:function(picPath){
    console.log("预览图片")
    Taro.previewImage({
      current: picPath, // 当前显示图片的http链接
      urls: [picPath] // 需要预览的图片http链接列表
    })
  },
  //上传图片
  uploadPic:function(){
      Taro.chooseImage({
          success (res) {
            const tempFilePaths = res.tempFilePaths
            Taro.uploadFile({
              url: 'https://example.weixin.qq.com/upload', //仅为示例，非真实的接口地址
              filePath: tempFilePaths[0],
              name: 'file',
              formData: {
                'user': 'test'
              },
              success (res){
                const data = res.data
                console.log(data)
                //do something
              }
            })
          }
      })
  },
  getFileName:function(path){
    var pos1 = path.lastIndexOf('/');
    var pos2 = path.lastIndexOf('\\');
    var pos  = Math.max(pos1, pos2);
    if( pos<0 )
        return path;
    else
        return path.substring(pos+1);
  },
  //获取文件后缀名
  getSuffix:function(name){
    if(name.lastIndexOf('.') == -1){
      return undefined
    }
    return name.substring(name.lastIndexOf('.') + 1)
  },
  //时间换算成多少天、小时、分钟
  getTimeOfSubmission:function(ISO8601time){
    if(!ISO8601time) return {}
    let updateTime:number = new Date(ISO8601time.replace(/-/g, "/")).getTime()
    let nowTime:number = Date.now()
    let newTime:number = nowTime - updateTime
    let day = parseInt((newTime / (24*3600*1000)).toString())
    let hour = parseInt((newTime % (24*3600*1000)/(3600*1000)).toString())
    let minute = parseInt((((newTime % (24*3600*1000)) % (3600*1000)) / (60*1000)).toString())
    return {day:day,hour:hour,minute:minute}
  },
  //设置全局数据&获取全局数据
  setStorage:function(key,value){
    setGlobalData(key,value)
    if(value == undefined){
      storage.set("MyUtilsPackage-"+key,value)
    }else{
      storage.set("MyUtilsPackage-"+key,JSON.stringify(value))
    }
    
    // return setGlobalData(key,value)
  },
  getStorage:function(key){
    if(getGlobalData(key)){
      return getGlobalData(key)
    }else if( storage.get("MyUtilsPackage-"+key) && storage.get("MyUtilsPackage-"+key) != "undefined"){
      return JSON.parse(storage.get("MyUtilsPackage-"+key))
    }else{
      console.log(key,"返回undefined")
      return undefined
    }
  },

  getfileName(path){//用来获取图片名字
    let pos = path.lastIndexOf('/')
    if( pos<0 ){
        return path;
    }else{
        return path.substring(pos+1);
    }
  },
  getPlainText(richCont){//提取富文本中的文字
    const str = richCont;
    let value = richCont;
    if(richCont){
        // 方法一： 
        // value= value.replace(/\s*/g, "");  //去掉空格
        value= value.replace(/<[^>]+>/g, ""); //去掉所有的html标记
        // value = value.replace(/↵/g, "");     //去掉所有的↵符号
        // value = value.replace(/[\r\n]/g, "") //去掉回车换行
        // value = value.replace(/&nbsp;/g, "") //去掉空格
        value = MyUtils.convertIdeogramToNormalCharacter(value);
        return value;
      } else {
        return null;
    }
  },
  convertIdeogramToNormalCharacter(val) {
    const arrEntities = {'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
    return val.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
  },
  isObjEqual(o1,o2){//比较两个对象是否相同
    var props1 = Object.getOwnPropertyNames(o1);
    var props2 = Object.getOwnPropertyNames(o2);
    if (props1.length != props2.length) {
      return false;
    }
    for (var i = 0,max = props1.length; i < max; i++) {
      var propName = props1[i];
      if (o1[propName] !== o2[propName]) {
        return false;
      }
    }
    return true;
  },

  parseUrl(str){//JS正则表达式解析URL(协议/域名/端口/路径/参数/锚点)
    if (!this.parseUrl || !this.parseUrl.options) {
        this.parseUrl.options = {
            strictMode: false,
            key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
            q: {
                name: "queryKey",
                parser: /(?:^|&)([^&=]*)=?([^&]*)/g
            },
            parser: {
                strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
                loose: /^(  ?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
            }
        };
    }
    if (!str) {
        return '';
    }
    var o = this.parseUrl.options,
        m = o.parser["strict"].exec(str),
        uri = {},
        i = 14;
    while (i--) uri[o.key[i]] = m[i] || "";
    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });
    return uri;
  },
  //数组分组,data传入的数组数据，num要分成多少个一组
  groupingArray(data,num){
    let result:any[] = [];
    for (var i = 0; i < data.length; i += num) {
        result.push(data.slice(i, i + num));
    }
    return result;
  },

  getUnitNum(data){//获取数字和单位，传入如10px、23rem等
    let unit = data.replace(/[0-9]*/g, '').replace(/\./, '') //获取单位
    let num = data.replace(unit,'')//获取数字
    return {num,unit}
  }
}

export default MyUtils 